package jnpf.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import jnpf.base.UserInfo;
import jnpf.model.zxgl_aIAssistant.ZXGL_AI_UploadKnowledge;
import jnpf.model.zxgl_aIAssistant.ZXGL_AiTopicinsert;
import jnpf.model.zxgl_aIAssistant.ZXGL_SeeChat;
import jnpf.model.zxgl_lixiangguanli.ZXGL_AI_Param;
import jnpf.model.zxgl_lixiangguanli.ZXGL_AI_QueryAIProcessing;
import jnpf.model.zxgl_xmcfzgbmjs.ZXGL_AI_responsibility;
import jnpf.model.zxgl_renwufankui.ZXGL_AI_Task;
import jnpf.model.zxgl_xiangmufankui.ZXGL_AI_ProjectEvaluation;
import jnpf.config.AIConfig;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ZXGL_DuBanXiangMu
 * 版本： V2.0
 * 版权： 河北交投智能交通技术有限责任公司
 * 作者： 数字交投项目组
 * 日期： 2025-03-19
 */
@Component
public class AIUtil {

    private static final Logger logger = LoggerFactory.getLogger(AIUtil.class);

    @Resource
    private UserProvider userProvider;

    @Resource
    private ObjectMapper mapper;

    @Resource
    private AIConfig aiConfig;

    /**
     * @Description:获取token接口
     * @Author: ZhaoChenXu
     * @Date: 2025-03-20
     * @return: java.lang.String
     **/
    public String getAiToken() {
        UserInfo userInfo = userProvider.get();
        Map<String, Object> queryParams = new HashMap<>();
        // queryParams.put("username", userInfo.getUserName());
        // logger.info("username:{}----->" + userInfo.getUserName());
        // logger.info("userid:{}----->" + userInfo.getUserId());
        queryParams.put("username", "test001");
        Map<String, String> headers = new HashMap<>();
        headers.put("X-API-Key", "35ad18e57dd34852bb6978bc8e40f560");
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        //先获取token信息：
        // String url = "https://jhzy.hebitt.com/aiapi/qa/api/token/get/" + userInfo.getUserId();
        // String url = "https://jhzy.hebitt.com/aiapi/qa/api/token/get/abcd1234";
        String url = aiConfig.getUrl() + "/api/token/get/abcd1234";
        JSONObject jsonObjectResult = hutoolGet(url, queryParams, headers);
        logger.info("获取token信息：{}--------->" + jsonObjectResult.toJSONString());
        if (jsonObjectResult.getBoolean("success")) {
            String token = jsonObjectResult.getString("data");
            return token;
        } else {
            return null;
        }
    }


    /**
     * @param token:令牌token
     * @param zxgl_ai_param:接口前端参数
     * @param bytes:文件byte
     * @Description:
     * @Author: ZhaoChenXu
     * @Date: 2025-03-20
     * @return: java.lang.String
     **/
    public String allocationProjectByDep(String token, ZXGL_AI_Param zxgl_ai_param, byte[] bytes) {

        logger.info("bytes:{}---------->" + bytes);
        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "multipart/form-data");
        headersAi.put("Authorization", token);

        //组装请求AI接口参数
        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("flowId", zxgl_ai_param.getFlowId());
        mapParam.put("callbackUrl", zxgl_ai_param.getCallbackUrl());
        // mapParam.put("callbackUrl", "http://124.70.101.31:30000/xtbgapi/zxgl/ZXGL_LiXiangGuanLi/matchDepartment");

        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/api/aiAllocation/project/upload";
        String urlDepartment = aiConfig.getUrl() + "/api/aiAllocation/project/upload";
        logger.info("mapParam:{}--------->" + mapParam.toString());
        JSONObject jsonResult = hutoolPost(urlDepartment, mapParam, headersAi, bytes, zxgl_ai_param.getZxglFileInfo().getName());
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());

        if (jsonResult.getBoolean("success")) {
            return "返回成功";
        } else {
            return null;
        }
    }

    /**
     * 部门确认
     *
     * @param token
     * @param zxgl_ai_responsibility
     * @param bytes
     * @return
     */
    public String allocationProjectByPerson(String token, ZXGL_AI_responsibility zxgl_ai_responsibility, byte[] bytes) {

        logger.info("bytes:{}---------->" + bytes);
        try {
            logger.info("zxgl_ai_task:{}---------->" + mapper.writeValueAsString(zxgl_ai_responsibility));
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }

        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "multipart/form-data");
        headersAi.put("Authorization", token);

        //组装请求AI接口参数
        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("flowId", zxgl_ai_responsibility.getFlowId());
        mapParam.put("callbackUrl", zxgl_ai_responsibility.getCallbackUrl());
        String result = "";
        try {
            result = mapper.writeValueAsString(zxgl_ai_responsibility.getZxgl_ai_projectInfo());
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }

        mapParam.put("projectInfo", result);
        logger.info("mapParam:{}---------->" + mapParam.toString());
        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/api/aiAllocation/responsibility/upload";
        String urlDepartment = aiConfig.getUrl() + "/api/aiAllocation/responsibility/upload";
        JSONObject jsonResult = hutoolPost(urlDepartment, mapParam, headersAi, bytes, zxgl_ai_responsibility.getZxgl_fileInfo().getName());
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());

        if (jsonResult.getBoolean("success")) {
            return "返回成功";
        } else {
            return null;
        }
    }

    /**
     * 项目分解任务
     *
     * @param token
     * @param zxgl_ai_task
     * @param bytes
     * @return
     */
    public String allocationProjectTask(String token, jnpf.model.zxgl_xiangmufenjie.ZXGL_AI_Task zxgl_ai_task, byte[] bytes) {

        logger.info("bytes:{}---------->" + bytes);
        try {
            logger.info("zxgl_ai_task:{}---------->" + mapper.writeValueAsString(zxgl_ai_task));
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }

        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "multipart/form-data");
        headersAi.put("Authorization", token);

        //组装请求AI接口参数
        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("flowId", zxgl_ai_task.getFlowId());
        mapParam.put("projectId", zxgl_ai_task.getProjectId());
        String projectInfo = "";
        try {
            projectInfo = mapper.writeValueAsString(zxgl_ai_task.getZxgl_ai_projectInfo());
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }
        mapParam.put("projectInfo", projectInfo);
        if (!StringUtil.isEmpty(zxgl_ai_task.getMeetingName())) {
            mapParam.put("meetingName", zxgl_ai_task.getMeetingName());
        }

        mapParam.put("callbackUrl", zxgl_ai_task.getCallbackUrl());
        logger.info("mapParam:{}---------->" + mapParam.toString());

        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/api/aiAllocation/project/task";
        String urlDepartment = aiConfig.getUrl() + "/api/aiAllocation/project/task";
        JSONObject jsonResult = hutoolPost(urlDepartment, mapParam, headersAi, bytes, zxgl_ai_task.getZXGL_FileInfo().getName());
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());

        if (jsonResult.getBoolean("success")) {
            return jsonResult.getString("data");
        } else {
            return null;
        }
    }


    /***
     * .AI 项目评估与评分
     * @param token
     * @param zxglAiProjectEvaluation
     * @param
     * @return
     */
    public String allocationProjectFk(String token, ZXGL_AI_ProjectEvaluation zxglAiProjectEvaluation, List<ZXGL_AI_UploadKnowledge> knowledges) {
        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "multipart/form-data");
        headersAi.put("Authorization", token);


        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("flowId", zxglAiProjectEvaluation.getFlowId());
        mapParam.put("callbackUrl", zxglAiProjectEvaluation.getCallbackUrl());
        //组装请求AI接口参数

        String projectInfo = "";
        try {
            projectInfo = mapper.writeValueAsString(zxglAiProjectEvaluation.getZXGL_ProjectInfoVO());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        mapParam.put("projectInfo", projectInfo);

        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/api/evaluation/project/upload";
        String urlDepartment = aiConfig.getUrl() + "/api/evaluation/project/upload";
        JSONObject jsonResult = hutoolPost(urlDepartment, mapParam, headersAi, knowledges);
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());
        if (jsonResult.getBoolean("success")) {
            return jsonResult.getString("data");
        } else {
            return null;
        }
    }

    /**
     * 任务反馈AI
     *
     * @param token
     * @param zxgl_ai_task
     * @param knowledges
     * @return
     */
    public String allocationTask(String token, ZXGL_AI_Task zxgl_ai_task, List<ZXGL_AI_UploadKnowledge> knowledges) {

        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "multipart/form-data");
        headersAi.put("Authorization", token);

        //组装请求AI接口参数
        Map<String, Object> mapParam = new HashMap<>();
        mapParam.put("flowId", zxgl_ai_task.getFlowId());

        String taskInfo = "";
        try {
            taskInfo = mapper.writeValueAsString(zxgl_ai_task.getTaskInfo());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        mapParam.put("taskInfo", taskInfo);
//        mapParam.put("projectName", zxgl_ai_task.getProjectName());
//        mapParam.put("taskName", zxgl_ai_task.getTaskName());
//        mapParam.put("currentProgress", zxgl_ai_task.getCurrentProgress());
//        mapParam.put("plannedValue", zxgl_ai_task.getPlannedValue());
//        mapParam.put("actualValue", zxgl_ai_task.getActualValue());

        mapParam.put("callbackUrl", zxgl_ai_task.getCallbackUrl());

        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/api/evaluation/task/upload";
        String urlDepartment = aiConfig.getUrl() + "/api/evaluation/task/upload";
        JSONObject jsonResult = hutoolPost(urlDepartment, mapParam, headersAi, knowledges);
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());

        if (jsonResult.getBoolean("success")) {
            return jsonResult.getString("data");
        } else {
            return null;
        }
    }

    /**
     * 查询结果
     *
     * @param token
     * @param zxgl_ai_queryAIProcessing
     * @return
     */
    public JSONObject queryAiProcessing(String token, ZXGL_AI_QueryAIProcessing zxgl_ai_queryAIProcessing) {

        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "application/json");
        headersAi.put("Authorization", token);

        //组装请求AI接口参数
        String json = "";
        try {
            json = mapper.writeValueAsString(zxgl_ai_queryAIProcessing);
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }
        logger.info("----------------------------------------------");
        logger.info("jsonResult:{}----->" + json);
        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/api/queryAiProcessing";
        String urlDepartment = aiConfig.getUrl() + "/api/queryAiProcessing";
        JSONObject jsonResult = hutoolPost(urlDepartment, json, headersAi);
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());

        return jsonResult;
//        if (jsonResult.getBoolean("success")) {
//            return jsonResult.getJSONObject("data");
//        } else {
//            return null;
//        }
    }

    // region 智能问答

    /**
     * AI 助手-创建主题接口（只有新开主题并且当问题发送出去的时候才会调用）
     *
     * @param token
     * @param topicName
     * @return 返回主题Id（字符串类型）
     */
    public String aiTopicinsert(String token, ZXGL_AiTopicinsert zXGL_AiTopicinsert) {
        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "application/json");
        headersAi.put("Authorization", token);

        //组装请求AI接口参数
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("topicName", zXGL_AiTopicinsert.getTopicName());
        jsonParam.put("assistantId", -6);
        jsonParam.put("platform", 4);
        jsonParam.put("projectName", zXGL_AiTopicinsert.getProjectName());
        jsonParam.put("projectId", zXGL_AiTopicinsert.getProjectId());

        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/aiTopic/insert";
        String urlDepartment = aiConfig.getUrl() + "/aiTopic/insert";
        JSONObject jsonResult = hutoolPost(urlDepartment, jsonParam.toString(), headersAi);
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());

        if (jsonResult.getBoolean("success")) {
            return jsonResult.getString("data");
        } else {
            return null;
        }
    }

    /**
     * AI 助手-智能问答接口（问答范围：所属项目的知识库相关项目文档）
     *
     * @param token
     * @param seeChat
     * @return
     */
    public String sseChat(String token, ZXGL_SeeChat seeChat) {
        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "application/json");
        headersAi.put("Authorization", token);

        seeChat.setAssistantId(-6);
        seeChat.setDialogueType(9);
        seeChat.setPlatform(4);

        //组装请求AI接口参数
        String jsonStr = "";
        try {
            jsonStr = mapper.writeValueAsString(seeChat);
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }

        //String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/sse/chat";
        String urlDepartment = aiConfig.getUrl() + "/sse/chat";
        String str = hutoolPostToStr(urlDepartment, jsonStr.toString(), headersAi);
        logger.info("jsonResult:{}----->" + str);
        return str;
//        if (jsonResult.getBoolean("success")) {
//            return jsonResult.getString("data");
//        } else {
//            return null;
//        }
    }

    /**
     * AI 助手-主题列表接口（分页查询，默认当前第1页 每页10条，创建时间倒序返回）
     *
     * @param token
     * @return
     */
    public String aiTopicQueryPage(String token, String projectId) {
        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "application/json");
        headersAi.put("Authorization", token);

        //组装请求AI接口参数
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("projectId", projectId);
        jsonParam.put("assistantId", -6);
        jsonParam.put("platform", 4);

        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/aiTopic/queryPage";
        String urlDepartment = aiConfig.getUrl() + "/aiTopic/queryPage";
        JSONObject jsonResult = hutoolPost(urlDepartment, jsonParam.toString(), headersAi);
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());

        if (jsonResult.getBoolean("success")) {
            return jsonResult.getString("data");
        } else {
            return null;
        }
    }

    /**
     * AI 助手-会话列表接口（分页查询，默认当前第1页 每页10条，创建时间倒序返回）
     *
     * @param token
     * @param topicId
     * @return
     */
    public String aiSessionQueryPage(String token, String topicId) {
        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "application/json");
        headersAi.put("Authorization", token);

        //组装请求AI接口参数
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("topicId", topicId);
        jsonParam.put("assistantId", -6);
        jsonParam.put("platform", 4);

        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/aiSession/queryPage";
        String urlDepartment = aiConfig.getUrl() + "/aiSession/queryPage";
        JSONObject jsonResult = hutoolPost(urlDepartment, jsonParam.toString(), headersAi);
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());

        if (jsonResult.getBoolean("success")) {
            return jsonResult.getString("data");
        } else {
            return null;
        }
    }

    /**
     * 删除主题
     *
     * @param token
     * @param idList
     * @return
     */
    public Boolean aiTopicDelete(String token, List<Integer> idList) {
        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "application/json");
        headersAi.put("Authorization", token);

        //组装请求AI接口参数
        logger.info("idList" + idList.toString());
        Map<String, Object> mapParam = new HashMap<>();
        String a1 = Joiner.on(",").join(idList);
        logger.info("mapParam:{}----->" + a1);
        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/aiTopic/delete";
        String urlDepartment = aiConfig.getUrl() + "/aiTopic/delete?idList=" + a1;
        JSONObject jsonResult = hutoolDelete(urlDepartment, headersAi);
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());

        if (jsonResult.getBoolean("success")) {
            return jsonResult.getBoolean("data");
        } else {
            return null;
        }
    }
    // endregion

    /**
     * 反馈上传/创建知识库
     *
     * @param token
     * @param mapParam
     * @param Knowledges
     * @return
     */
    public JSONObject uploadKnowledgeBase(String token, Map<String, Object> mapParam, List<ZXGL_AI_UploadKnowledge> Knowledges) {

        //调用智能立项接口
        Map<String, String> headersAi = new HashMap<>();
        headersAi.put("Content-Type", "multipart/form-data");
        headersAi.put("Authorization", token);

        // String urlDepartment = "https://jhzy.hebitt.com/aiapi/qa/api/uploadKnowledgeBase";
        String urlDepartment = aiConfig.getUrl() + "/api/uploadKnowledgeBase";
        JSONObject jsonResult = hutoolPost(urlDepartment, mapParam, headersAi, Knowledges);
        logger.info("jsonResult:{}----->" + jsonResult.toJSONString());
        return jsonResult;
    }


    // region 辅助方法

    /**
     * @param byteArray:流
     * @param fileName:文件名
     * @Description:将文件流转成File
     * @Author: ZhaoChenXu
     * @Date: 2025-03-20
     * @return: java.io.File
     **/
    public static File convertByteArrayToFile(byte[] byteArray, String fileName) throws IOException {

        File tempFile = Files.createTempFile(fileName, null).toFile();
        try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
            fileOutputStream.write(byteArray);
            return tempFile;
        }
    }

    /**
     * @param file:
     * @Description:将File转成MultipartFile
     * @Author: ZhaoChenXu
     * @Date: 2025-03-20
     * @return: org.springframework.web.multipart.MultipartFile
     **/
    public MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    private static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    public JSONObject hutoolGet(String url, Map<String, Object> queryParams, Map<String, String> headers) {
        String body = HttpRequest.get(url).form(queryParams).addHeaders(headers).execute().body();
        return JSONObject.parseObject(body);
    }

    public JSONObject hutoolPost(String url, Map<String, Object> map, Map<String, String> headers, byte[] bytes, String fileName) {
        try {
            HttpRequest request = HttpRequest.post(url).form(map);
            if (bytes != null && bytes.length > 0) {
                request.form("meetingFile", bytes, fileName);
            }
            String body = request.setConnectionTimeout(60000).setReadTimeout(60000).addHeaders(headers).execute().body();
            return JSONObject.parseObject(body);
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg", e.getMessage());
            return jsonObject;

        }
    }

    public JSONObject hutoolPost(String url, Map<String, Object> map, Map<String, String> headers, List<ZXGL_AI_UploadKnowledge> knowledges) {
        try {
            HttpRequest request = HttpRequest.post(url).form(map);
            for (ZXGL_AI_UploadKnowledge knowledge : knowledges) {
                request.form("attachments", knowledge.getBytes(), knowledge.getName());
            }
            String body = request.setConnectionTimeout(60000).setReadTimeout(60000).addHeaders(headers).execute().body();
            return JSONObject.parseObject(body);
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg", e.getMessage());
            return jsonObject;

        }
    }

    public JSONObject hutoolPost(String url, String json, Map<String, String> headers) {
        try {
            String body = HttpRequest.post(url).body(json).setConnectionTimeout(60000).setReadTimeout(60000).addHeaders(headers).execute().body();
            return JSONObject.parseObject(body);
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg", e.getMessage());
            return jsonObject;

        }
    }

    public String hutoolPostToStr(String url, String json, Map<String, String> headers) {
        try {
            String body = HttpRequest.post(url).body(json).setConnectionTimeout(60000).setReadTimeout(60000).addHeaders(headers).execute().body();
            return body;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public byte[] downloadFile(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
//            FileOutputStream outputStream = new FileOutputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();
            logger.info("文件下载成功");
            return outputStream.toByteArray();
        } else {
            logger.info("文件下载失败，响应码: " + responseCode);
        }
        connection.disconnect();
        return null;
    }

    public JSONObject hutoolDelete(String url, Map<String, String> headers) {
        try {
            String body = HttpRequest.delete(url).setConnectionTimeout(60000).setReadTimeout(60000).addHeaders(headers).execute().body();
            return JSONObject.parseObject(body);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg", e.getMessage());
            return jsonObject;

        }
    }

    // endregion
}
